package com.bsoft.gol.hcs.specialist.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.*;
import com.bsoft.gol.hcs.clinical.bean.response.*;
import com.bsoft.gol.hcs.clinical.bean.vo.ConsultAskVo;
import com.bsoft.gol.hcs.clinical.dao.*;
import com.bsoft.gol.hcs.clinical.entity.AppDoctor;
import com.bsoft.gol.hcs.clinical.entity.HoConsultAsk;
import com.bsoft.gol.hcs.common.bean.response.ParameterResponse;
import com.bsoft.gol.hcs.common.service.BaseDataService;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import com.bsoft.gol.hcs.enumcase.GolSysParameterEnum;
import com.bsoft.gol.hcs.enumcase.SysParameterEnum;
import hcn.util.BaseResponse;
import hcn.service.commonClinical.qo.SysParameterRequest;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.service.IMedicalSkillsHisService;
import com.bsoft.gol.hcs.his.service.IMedicalSkillsHisXmlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import service.rpc.DoctorInfoServiceIntf;
import com.bsoft.gol.hcs.service.rpc.IBaseParameterService;
import service.rpc.IOrganizationRpcService;
import com.bsoft.gol.hcs.specialist.service.IMedicalSkillsService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 接口类型，Constants.GOL 调用健康通，Constants.HOL调用互联网医院
 * @Author: zhaorb
 * @Date: 2020/6/22 15:03
 **/
@SsdevService("specialistMedicalSkillsService")
public class MedicalSkillsService implements IMedicalSkillsService {

    private static final Logger logger = LoggerFactory.getLogger(MedicalSkillsService.class);

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    ExamineRequisitionRecordDAO examineRequisitionRecordDAO;
    @Autowired
    ExamineRequisitionDetailDAO examineRequisitionDetailDAO;
    @Autowired
    CheckRequisitionRecordDAO checkRequisitionRecordDAO;
    @Autowired
    CheckRequisitionDetailDAO checkRequisitionDetailDAO;
    @Autowired
    CheckAppointmentRecordDAO checkAppointmentRecordDAO;
    @Autowired
    ConsultAskDAO consultAskDAO;
    @Autowired
    OdsDiagnosisDAO odsDiagnosisDAO;
    @Autowired
    AppDoctorDAO appDoctorDAO;
    @Autowired
    AccountDAO accountDAO;
    @Autowired
    BaseDataService baseDataService;

    @Autowired
    DoctorInfoServiceIntf doctorInfoRpcService;
    @Autowired
    private IMedicalSkillsHisService medicalSkillsHisService;
    @Autowired
    private IMedicalSkillsHisXmlService medicalSkillsHisXmlService;
    @Autowired
    IBaseParameterService baseParameterService;
    @Value("${project_source}")
    private String projectSource;
    @Value("${phis_path_url}")
    public String PHIS_PATH_URL;
    @Autowired
    private IOrganizationRpcService organizationRpcService;

    /**
     * @Description: 获取检查类型
     * @Author: zhaorb
     * @Date: 2020/6/4 15:24
     **/
    @Override
    @RpcService
    public CheckTypeTotalResponse queryCheckTypeList(CheckTypeRequest request) throws ControllerException {
        String orgId = request.getOrganizationId();
        request.setOrganizationId(this.getNoCorp(request.getOrganizationId()));
        return medicalSkillsHisXmlService.queryCheckTypeList(request).getData();
//        if (this.getFormatInterfaceExchange(orgId)) {
//            return medicalSkillsHisService.queryCheckTypeList(request).getData();
//        } else {
//            return medicalSkillsHisXmlService.queryCheckTypeList(request).getData();
//        }
    }

    /**
     * @Description: 检查开单对接方式
     * @Author: zhaorb
     * @Date: 2020/9/23 13:15
     **/
    private boolean getFormatInterfaceExchange(String orgId) {
        SysParameterRequest req = new SysParameterRequest();
        req.setType(projectSource);
        List<String> strings = new ArrayList<>();
        if (Constants.HOL.equals(projectSource)) {
            strings.add(SysParameterEnum.FORMAT_INTERFACE_EXCHANGE.getParameterKey());
        } else {
            req.setOrganizationId(orgId);
            //strings.add("013701");
            strings.add(GolSysParameterEnum.FORMAT_INTERFACE_EXCHANGE.getParameterKey());
        }
        req.setParameterKeyList(strings);
        List<ParameterResponse> list = baseParameterService.getSysParameterList(req).getData();
        if (CommonUtils.isNotEmpty(list)) {
            String value = list.get(0).getParameterValue();
            if (Constants.HOL.equals(projectSource)) {
                if ("1".equals(value)) {
                    // 互联网医院 接口数据交换格式 1 XML，2 JSON
                    return false;
                } else {
                    return true;
                }
            } else {
                // 健康通 检查开单对接方式(0:json 1:xml)
                if ("1".equals(value)) {
                    return false;
                } else {
                    return true;
                }
            }
        }
        return true;
    }


    private String getNoCorp(String organizationId) {
        if (Constants.GOL.equals(projectSource)) {
            return organizationId;
        } else {
            SysParameterRequest req = new SysParameterRequest();
            req.setType(projectSource);
            List<String> strings = new ArrayList<>();
            strings.add(SysParameterEnum.CM_MULTI_HOSPITAL_CODE.getParameterKey());
            req.setParameterKeyList(strings);
            List<ParameterResponse> list = baseParameterService.getSysParameterList(req).getData();
            if (CommonUtils.isNotEmpty(list)) {
                return list.get(0).getParameterValue();
            }
            return organizationId;
        }
    }


    /**
     * @Description: 获取检查单项目列表
     * @Author: zhaorb
     * @Date: 2020/6/4 15:24
     **/
    @Override
    @RpcService
    public QueryCheckItemResponse queryCheckItemList(QueryCheckItemListReq request) throws ControllerException{
        String orgId = request.getOrganizationId();
        request.setOrganizationId(getNoCorp(request.getOrganizationId()));
        QueryCheckItemResponse response = new QueryCheckItemResponse();
        List<QueryCheckItemListResp> listResps = medicalSkillsHisXmlService.queryCheckItemList(request);
//        if (getFormatInterfaceExchange(orgId)) {
//            listResps = medicalSkillsHisService.queryCheckItemList(request);
//        } else {
//            listResps = medicalSkillsHisXmlService.queryCheckItemList(request);
//        }
        if (CommonUtils.isNotEmpty(listResps)) {
            //去重list
            List<QueryCheckItemListResp> resList = listResps.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(QueryCheckItemListResp::getExamMajorItemId))),ArrayList::new));
            response.setList(resList);
            response.setExecuteDepartmentId(resList.get(0).getExecuteDepartmentId());
            response.setExecuteDepartmentName(resList.get(0).getExecuteDepartmentName());
            QueryMedicalSkillListReq req = new QueryMedicalSkillListReq();
            req.setConsultId(request.getConsultId());
            ConsultAskVo consultAsk = getConsultAsk(req).getData();
            if (CommonUtils.isNotEmpty(req.getConsultId())) {
                if (CommonUtils.isNotEmpty(consultAsk)) {
                    //保存列表
                    response.setOpenDoctorId(consultAsk.getDoctorId());
                    response.setOpenDoctorName(consultAsk.getDoctorName());
                    response.setOpenDepartmentId(consultAsk.getDepartmentId());
                    response.setOpenDepartmentName(consultAsk.getDepartmentName());
                } else {
                    throw new ControllerException("问诊id不存在");
                }
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            response.setOpenTime(df.format(new Date()));
        }
        return response;
    }

    /**
     * @Description: 获取项目部位和方法（HIS）
     * @Author: xuxy
     * @Date: 2020/6/4 16:12
     **/
    @Override
    @RpcService
    public QueryCheckPositionListResp queryCheckPositionList(QueryCheckPositionListReq request) throws ControllerException {
        String orgId = request.getOrganizationId();
        request.setOrganizationId(getNoCorp(request.getOrganizationId()));
        QueryCheckPositionListResp result = new QueryCheckPositionListResp();
        List<CheckPositionItemRequest> list = new ArrayList<>();
        QueryCheckItemListReq req = new QueryCheckItemListReq();
        req.setOrganizationId(request.getOrganizationId());
        req.setExamTypeId(request.getExamTypeId());
        List<QueryCheckItemListResp> listResps = medicalSkillsHisXmlService.queryCheckItemList(req);
//        if (getFormatInterfaceExchange(orgId)) {
//            listResps = medicalSkillsHisService.queryCheckItemList(req);
//        } else {
//            listResps = medicalSkillsHisXmlService.queryCheckItemList(req);
//        }
        List<QueryCheckItemListResp> filters = listResps.stream()
                .filter(resp -> request.getExamMajorItemId().equals(resp.getExamMajorItemId()))
                .collect(Collectors.toList());
        if (CommonUtils.isNotEmpty(filters)) {
            QueryCheckItemListResp listResp = filters.get(0);
            List<QueryCheckPositionItemResp> resps;
            if (getFormatInterfaceExchange(request.getOrganizationId())) {
                resps = medicalSkillsHisService.queryCheckPositionList(request);
            } else {
                resps = medicalSkillsHisXmlService.queryCheckPositionList(request);
            }
            CheckPositionItemRequest check = new CheckPositionItemRequest();
            BeanUtils.copyProperties(listResp, check);
            check.setItemList(resps);
            list.add(check);
        }
        result.setList(list);
        result.setTotal(list.stream().count());
        return result;

    }

    private BaseResponse<ConsultAskVo> getConsultAsk(QueryMedicalSkillListReq request) {
        BaseResponse<ConsultAskVo> response = new BaseResponse<>();
        ConsultAskVo vo = new ConsultAskVo();
        try {
            if (Constants.HOL.equals(projectSource)) {
                logger.info("进入互联网医院");
                HoConsultAsk consultAsk = null;
                if (CommonUtils.isNotEmpty(request.getConsultId())) {
                    consultAsk = consultAskDAO.getConsultAskAll(request);
                } else {
                    consultAskDAO.getConsultAskByEmergencyNumber(request.getHospitalCode(), request.getVisitNo());
                }
                BeanUtils.copyProperties(consultAsk, vo);
                vo.setPatientIdentityCardType("0" + consultAsk.getPatientIdentityCardType());
                if (CommonUtils.isNotEmpty(consultAsk)) {
                    List<AppDoctor> appDoctors = appDoctorDAO.queryAppDoctor(consultAsk.getDoctorCode());
                    if (CommonUtils.isNotEmpty(appDoctors)) {
                        AppDoctor appDoctor = appDoctors.get(0);
                        vo.setDoctorUserId(String.valueOf(appDoctor.getUid()));
                    }
                }
                vo.setPatientMedicalCardType(String.valueOf(consultAsk.getPatientMedicalCardType()));
                vo.setConsultId(consultAsk.getConsultId() + "");
                vo.setLocalOrgId(consultAsk.getHospitalCode());
            } else {
                logger.info("进入智慧健康通");
                vo = medicalSkillsHisService.getHcnConsultAsk(request).getData();
            }
            if (CommonUtils.isNotEmpty(vo)) {
                response.setData(vo);
                response.setCode(ResultCode.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setMessage("获取问诊信息失败");
            response.setCode(ResultCode.ERROR);
        }
        return response;
    }

}
